package top.kaoshanji.p1ch05b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/11 17:59
 */
public class BuildingStreams {

    private static final Logger logger = LogManager.getLogger(BuildingStreams.class);

    public static void main(String[] args) {

        // 代码清单-p1ch05b-111页a：由值创建流
        logger.info("...由值创建流...");
        Stream<String> stream = Stream.of("Java 8", "Lambdas", "In", "Action");
        stream.map(String::toUpperCase).forEach(System.out::println);

        Stream<String> emptyStream = Stream.empty();


        // 代码清单-p1ch05b-112页a：由可空对象创建流
        logger.info("...由可空对象创建流...");
        Stream<String> homeValueStream = Stream.ofNullable(System.getProperty("home"));
        System.out.println(homeValueStream.collect(Collectors.joining()));



        // 代码清单-p1ch05b-112页b：由数组创建流
        logger.info("...由数组创建流...");
        int[] numbers = { 2, 3, 5, 7, 11, 13 };
        System.out.println(Arrays.stream(numbers).sum());



        // 代码清单-p1ch05b-112页c：由文件生成流
        logger.info("...由文件生成流...");
        long uniqueWords = 0;
        try (Stream<String> lines = Files.lines(Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("p1ch02a44页a\\data.txt")), Charset.defaultCharset())){
            uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" ")))
                    .distinct()
                    .count();
            System.out.println(uniqueWords);
        } catch (IOException e) {
            e.printStackTrace();
        }


        // 代码清单-p1ch05b-113页a：迭代
        logger.info("...迭代...");
        Stream.iterate(0, n -> n + 2).limit(10).forEach(System.out::println);



        // 代码清单-p1ch05b-115页a：生成
        logger.info("...生成...");
        Stream.generate(Math::random).limit(10).forEach(System.out::println);


    }

}
